package com.example.common.util.util_entity.core;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.*;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

@Data
public class Result<T> implements Serializable {
    private ResultHeader header;
    private T body = null;
    private Map<String, Object> extension;

    protected Result() {
        this.header = new ResultHeader(CommCode.SUCCESS);
        this.extension = new HashMap();
    }

    private Result(ResultHeader header, T body, Map<String, Object> extension) {
        this.header = header;
        this.extension = (Map)(extension == null ? new HashMap(0) : extension);
        this.body = body;
    }

    public static <T> Result<T> build() {
        return new Result(new ResultHeader(CommCode.SUCCESS), (Object)null, (Map)null);
    }

    @JSONField(
        serialize = false
    )
    public boolean isSuccess() {
        return CommCode.SUCCESS.getCode().equals(this.header.getCode());
    }

    public static <T> T ofNullable(Result<T> result) {
        return result != null && result.isSuccess() ? result.getBody() : null;
    }

    public static <T> T ofNullable(Result<T> result, T value) {
        return result != null && result.isSuccess() ? result.getBody() : value;
    }

    public static <T> Result<T> build(Code code) {
        return new Result(new ResultHeader(code), (Object)null, (Map)null);
    }

    public static <T> Result<T> build(ResultHeader header) {
        return new Result(header, (Object)null, (Map)null);
    }

    public static <T> Result<T> build(T body) {
        return new Result(new ResultHeader(CommCode.SUCCESS), body, (Map)null);
    }

    public static <T> Result<T> build(Code code, T body) {
        return new Result(new ResultHeader(code), body, (Map)null);
    }

    public static <T> Result<T> build(Code code, T body, Map<String, Object> extension) {
        return new Result(new ResultHeader(code), body, extension);
    }

}
